package com.example.captchademo.controller;

/*
 * @author zzr
 * @date: 2025/09/19  11:34
 * @description:
 */

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.example.captchademo.bean.CaptchaProperties;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;

@RequestMapping("/captcha")
@RestController
public class HuToolCaptchaController {

    @Autowired
    private CaptchaProperties captchaProperties;

    @RequestMapping("/getCaptcha")
    public void getCaptcha(HttpSession session, HttpServletResponse response) {

        // 定义图形验证码的长，宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(captchaProperties.getWidth(), captchaProperties.getHeight());
        // 设置响应 Content-Type
        response.setContentType("image/jpeg");
        // 禁止使用缓存
        response.setHeader("Pragma","No-cache");

        // 图形验证码写出
        try {
            // 输出到页面
            lineCaptcha.write(response.getOutputStream());
            // 存储在 session 中
            session.setAttribute(captchaProperties.getSession().getKey(),lineCaptcha.getCode());
            session.setAttribute(captchaProperties.getSession().getDate(), new Date());

            // 打印日志
            System.out.println("生成的验证码" + lineCaptcha.getCode());

            //关闭流
            response.getOutputStream().close();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    // 校验验证码
    private final static long VALID_MILLIS_TIME = 60 * 1000;
    @RequestMapping("/check")
    public boolean checkHomeCaptcha(String captcha, HttpSession session) {
        if (!StringUtils.hasLength(captcha)) {
            return false;
        }
        String savedCaptch = (String) session.getAttribute(captchaProperties.getSession().getKey());
        Date sessionDate = (Date) session.getAttribute(captchaProperties.getSession().getDate());

        if (savedCaptch == null || sessionDate == null) {
            return false;
        }

        if (captcha.equalsIgnoreCase(savedCaptch)) {
            // 判断是否超时
            if (System.currentTimeMillis() - sessionDate.getTime() < VALID_MILLIS_TIME) {
                return true;
            }
            return false;
        }
        return false;
    }
}
